﻿using Newtonsoft.Json;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoneLineNew.Models.Entity.BaseInfo;
using ZoneLineNew.Models.Entity.Template;
using ZoneLineNew.Services.DB;
using ZoneLineNew.Services.Message;
using ZoneLineNew.ViewModelBase;

namespace ZoneLineNew.ViewModels.Dialogs {
    public class EditViewTableDialogViewModel : DialogViewModel {

        public EditViewTableDialogViewModel(
            IRegionManager regionManager,
            IDialogService dialog,
            IEventAggregator eventAggregator,
            IMessageService message,
            IDbOperate<IFreeSqlMainContext> mainDbOperate)
            : base(regionManager, dialog, eventAggregator, message, mainDbOperate) {

            ViewTableEntity = new ViewTableEntity();
        }

        private ViewTableEntity viewTableEntity;


        public ViewTableEntity ViewTableEntity {
            get { return viewTableEntity; }
            set { viewTableEntity = value; base.RaisePropertyChanged(); }
        }


        public DelegateCommand SaveCommand => new DelegateCommand(() => {
            int affected = 0;
            if (!string.IsNullOrEmpty(ViewTableEntity.ViewTableName)) {
                affected = _mainDbOperate.GetFreeSql().InsertOrUpdate<ViewTableEntity>().SetSource(ViewTableEntity).ExecuteAffrows();
            } else {
                _message.Warning("对照表名称必填！");
                return;
            }

            if (affected >= 1) {
                base.OnDialogClosed(ButtonResult.OK);
            } else {
                _message.Error("编辑失败！");
            }
        });

        public DelegateCommand CancelCommand => new DelegateCommand(() => {
            base.OnDialogClosed(ButtonResult.Cancel);
        });


        protected override void OnViewLoaded() {

            if (_dialogParameters.ContainsKey("ViewTableEntity")) {

                ViewTableEntity = JsonConvert.DeserializeObject<ViewTableEntity>(_dialogParameters.GetValue<string>("ViewTableEntity"));
            }

        }


    }
}
